<template>
  <div class="excel-preivew-wp" ref="excelPreviewRef">
  	<div class="excel-scroll">
  		<div class="table-box">
	  		<div ref="tableBoxRef"></div>
		  	<div v-if="config.add" class="handle-box">
		  		<el-button @click="addRow()">添加行</el-button>
		  		<el-button @click="deleteRow()">删除行</el-button>
		  	</div>
	  	</div>
  	</div>
	  	

  	<!-- <div class="sub-box">
  		<el-button type="primary" @click="exportExcel()">导出EXCEL</el-button>
  		<el-button type="primary" @click="saveExcel()">保存</el-button>
  	</div> -->

  	<table class="gd-table" ref="gdTableRef">
  		<tbody></tbody>
  	</table>

  	<div class="gd-tools">
  		<div v-for="(item, index) in _d.gdTools" :key="item.domId">
  			<div :id="item.domId" class="operate_tool" :style="item.style">
  				<template v-if="item.type == 'input'">
	  				<el-input style="width:100%;" v-model="item.value" placeholder="请输入" @change="inputChange(item.domId)"/>
	  			</template>
	  			<template v-if="item.type == 'inputNumber'">
	  				<el-input-number style="width:100%;" v-model="item.value" placeholder="请输入" @change="inputChange(item.domId)"/>
	  			</template>
	  			<template v-if="item.type == 'textarea'">
	  				<el-input v-model="item.value" type="textarea" :rows="item.rows" placeholder="请输入" @change="inputChange(item.domId)"/>
	  			</template>
	  			<template v-if="item.type == 'text'">
	  				<div>{{item.value}}</div>
	  			</template>
  			</div>
  		</div>
  	</div>

  	<div ref="exportBoxRef" class="export-box"></div>
  </div>
</template>

<script setup>
	import { reactive, ref, watch, onMounted } from 'vue'
	import {getId, tableToExcel, copyToClipboard, downloadPDF} from "/@/utils/Tools.js"
	import { ElMessage } from 'element-plus'
	import request from '/@/utils/request';

	const excelPreviewRef = ref();
	const tableBoxRef = ref();
	const gdTableRef = ref();
	const exportBoxRef = ref();

	const props = defineProps({
		// 是否组件，组件数据使用props.config，页面数据使用接口
		isCmp: {
			type: Boolean,
			default: false
		},
		config: {
			type: Object,
			default: () => ({})
		}
	})

	// 如果是组件时，格式化数据
	watch(() => props.config, () => {
		initData();
	})

	const _d = reactive({
		// 配置
		config: {},
		// 添加的次数
		addNum: 0,
		// 过渡工具
		gdTools: [],
		// 工具
		table: {
			head: [],
			body: [],
			footer: []
		}

	})

	onMounted(() => {
		initData();
	})
	// 初始化数据
	function initData() {
		// 设置配置内容
		_d.config = JSON.parse(JSON.stringify(props.config));
		if(!_d.config.table) {
			return;
		}
		// 格式化tBody内容
		let oData = formateTable(props.config.table);
		// 设置table数据
		tableBoxRef.value.innerHTML = oData.html;
		// 设置过渡操作
		_d.gdTools = [...oData.tools];
		setTimeout(() => {
			replaceInput();
		}, 500);
	}

	// 格式化数据
	function formateTable(data) {
		let aArr = data.split('##');
		// 获取表格html，与操作组件
		let html = '';
		let tools = [];
		aArr.forEach((str, index) => {
			if(str.indexOf('json:') == 0) {
				let obj = JSON.parse(str.substring(5));
				obj.domId = 'operate_tool_'+getId(5);
				if(obj.type == 'inputNumber') {
					obj.value = Number(obj.value || 0);
				}
				html += `<div class="replace_box" data-id="${obj.domId}"></div>`;
				tools.push(obj);
			} else {
				html += str;
			}
		})

		return {
			html,
			tools
		}
	}

	// 替换输入框
	function replaceInput() {
		let aReplaceBox = excelPreviewRef.value.querySelectorAll('.replace_box');
		for(let i = 0; i < aReplaceBox.length; i++) {
			let oBox = aReplaceBox[i];
			let oIpt = document.getElementById(oBox.dataset.id);
			oBox.parentNode.replaceChild(oIpt, oBox);
		}
		// 获取表格工具列表
		getTableTools();
	}

	// 获取表格工具列表
	function getTableTools() {
		setTimeout(() => {
			let arr = [];
			_d.table.head = getTools(tableBoxRef.value.querySelector('thead'));
			_d.table.body = getTools(tableBoxRef.value.querySelector('tbody'));
			_d.table.footer = getTools(tableBoxRef.value.querySelector('tfooter'));
		}, 50);
	}

	// 获取当前选择器下的所有工具
	function getTools(dom) {
		let arr = [];
		if(!dom) {
			return arr;
		}
		let aTr = dom.querySelectorAll('tr');
		for(let i = 0; i < aTr.length; i++) {
			let oTr = aTr[i];
			let aTools = oTr.querySelectorAll('.operate_tool');
			let brr = [];
			for(let j = 0; j < aTools.length; j++) {
				let id = aTools[j].id;
				let obj = _d.gdTools.find(item => item.domId == id);
				brr.push(obj);
			}
			arr.push(brr);
		}
		return arr;
	}

	// 添加行
	function addRow() {
		if(_d.config.add) {
			let oData = formateTable(_d.config.add);
			// 设置过渡操作
			_d.gdTools.push(...oData.tools);
			// 设置节点
			let gdTbody = gdTableRef.value.querySelector('tbody');
			gdTbody.innerHTML = oData.html;
			setTimeout(() => {
				let children = gdTbody.children;
				let length = children.length;
				let tbody = tableBoxRef.value.querySelector('tbody');
				for(let i = 0; i < length; i++) {
					tbody.appendChild(children[0]);
				}
				setTimeout(() => {
					replaceInput();

					// 获取表格工具列表
					getTableTools();

					_d.addNum++;
				}, 50);
			}, 50);
		}
	}

	// 删除行
	function deleteRow() {
		if(_d.config.delete) {
			let code = `window.deleteFunction = function(oTbody, ElMessage) {${_d.config.delete}}`;
			eval(code);
			// 删除tr节点
			let isRemove = window.deleteFunction(tableBoxRef.value.querySelector('tbody'), ElMessage);
			if(!isRemove) {
				return;
			}
			// 获取表格工具列表
			getTableTools();

			_d.addNum--;
		}
	}

	// 行改变
	function inputChange(domId) {
		if(_d.config.change) {
			let code = `window.changeFunction = function(ElMessage, tableTools) {${_d.config.save}}`;
			eval(code);
			window.changeFunction(ElMessage, _d.table);
		}
	}

	// 导出
	function exportExcel() {
		// console.log(_d.gdTools);return;
		let html = _d.config.table;
		let arr = html.split('</tbody>');
		html = arr[0];
		for(let i = 0; i < _d.addNum; i++) {
			html += _d.config.add;
		}
		html += '</tbody>' + arr[1];
		let aHtml = html.split(/##[^##]+##/);
		let aTools = _d.gdTools;
		html = '';
		aHtml.forEach((item, index) => {
			html += item;
			if(index < aTools.length) {
				let oItem = aTools[index];
				// 格式化文本
				let value = oItem.value;
				if(typeof value == 'string') {
					value = formatText(oItem.value);
				}
				if(oItem.format) {
					eval('window.excelValueFormat = '+oItem.format);
					value = window.excelValueFormat(value);
				}
				html += value;
			}
		})
		exportBoxRef.value.innerHTML = html;

		setTimeout(() => {
			// 导出pdf
			downloadPDF(exportBoxRef.value, '测试');
		}, 100);
		
		// 执行导出excel
		// tableToExcel(html, 'excel模板');
	}

	// 格式化文本
	function formatText(text) {
		text = text.replace(/ /g, '&nbsp;');
		let arr = text.split('\n');
		text = arr.join('<br/>');
		return text;
	}

	// 保存
	function saveExcel() {
		// if(_d.config.save) {
		// 	let code = `window.saveFunction = function(request, ElMessage, tableTools) {${_d.config.save}}`;
		// 	eval(code);
		// 	window.saveFunction(request, ElMessage, _d.table);
		// }
		console.log(JSON.stringify(_d.config));
	}

	// 拷贝代码
	function copyCode() {
		copyToClipboard(JSON.stringify(_d.config));
	}

	// 获取代码
	function getCode() {
		return JSON.stringify(_d.config);
	}

	defineExpose({
		export: exportExcel,
		save: saveExcel,
		copy: copyCode,
		getCode: getCode
	})

</script>

<style lang="scss">
.excel-preivew-wp {
	position: relative;
	width: 100%;
	padding: 10px 10px 0;
	text-align: center;
	table {
		border-collapse: collapse;
	}
	.table-box {
		position: relative;
		display: inline-block;
		.handle-box {
			padding-top: 10px;
			text-align: center;
		}
	}

	.sub-box {
		padding: 20px 10px 0;
		text-align: center;
	}
		
	.gd-table {
		position: absolute;
		z-index: -101;
		bottom: 0;
		left: 0;
		opacity: 0;
	}

	.gd-tools {
		position: absolute;
		z-index: -100;
		bottom: 0;
		left: 0;
		opacity: 0;
	}
}

.export-box {
	position: fixed;
	z-index: -100;
	top: 0;
	left: 0;
	padding: 25px 0;
	background: #fff;
	table {
		margin: 0 auto;
	}
}
</style>